// subIndex/index/good-item/good-item.js
import Toast from '../../../miniprogram/miniprogram_npm/vant-weapp/toast/toast'

let app = getApp()
const moment = require('../../../utils/moment.min.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: '',
    goods: {},
    serverTime: null,//当前时间
    tabCartTotal: '',

    isSaling: '',//true 秒杀中
    notStart: '',//true 等待开始

    showSku: false,//规格弹框
    skuGoods: {
      id: '',
      detail: '',
      selectSku: '',//选中的规格
      selectNum: 1,//规格数量
    },

    heShopId: '',//分享者的门店id
    productId: '',//商品id
    goodsThumb: '',//分享的商品图
    goodsTitle: '',//分享的商品名
    commentInfo:{},//评论总详情

  },

  //接收分享商品图片，商品id
  shareGoodsIdSuffer (event) {
    this.setData({
      productId: event.detail.id,
      goodsThumb: event.detail.thumb,
      goodsTitle: event.detail.title,
    })
  },

  //查询商品详情数据
  getGoodInfo () {
    let _this = this
    if (_this.data.user.id == null) return
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/shop/products/detail',
      data: {
        productId: _this.data.productId,
        memberId: _this.data.user.id,
      },
      load: 1
    }).then((res) => {
      _this.setData({
        serverTime: res.data.time,
        goods: res.data.data
      })

      _this.isSalingFun()
      _this.notStartFun()

    })
  },

  //加入购物车
  addCartClick (event) {
    let _this = this;

    let goods = event.currentTarget.dataset['goods'];
    let plus = event.currentTarget.dataset['plus'];
    let skuData = event.currentTarget.dataset['skuData'];

    if(goods.hasoption == 1 && (!_this.data.showSku || goods.id != _this.data.skuGoods.id)) {//多规格商品
      if(!_this.data.skuGoods || goods.id != _this.data.skuGoods.id){
        app.requestUrl({
          method: 'GET',
          url: '/wxapi/shop/products/detail',
          data: {
            productId: goods.id,
            memberId: _this.data.user.id
          }
        }).then(res =>{
          _this.setData({
            skuGoods: goods,
            ['skuGoods.detail']: res.data.data,
            showSku: true,
          })
        })
      } else {
        _this.setData({  showSku: true })
      }
    } else {//加入购物车，包含多规格加入购物车
      //普通
      let cartItem = {
        mid: _this.data.user.id ? _this.data.user.id : '',
        centreId: app.globalData.loginCentreId,
        teamId: _this.data.user.upshopTid ? _this.data.user.upshopTid : '',//未登录需要传门店id
        openid: _this.data.user.openid ? _this.data.user.openid : '',
        productId: goods.id,
        total: plus ? 1 : -1,//plus=true加入购物车，plus=false减
        marketprice: (_this.data.user.isVip && goods.vipprice && goods.isvip && _this.data.user.vipofcentreId.indexOf(app.globalData.loginCentreId) != -1) ? goods.vipprice : goods.marketprice,//用户是会员+商品有会员价+商品是会员商品，取会员价
        vipprice: goods.vipprice,
      };
      //多规格
      if(_this.data.showSku && skuData){
        cartItem.total = skuData.selectNum;
        cartItem.skuId = skuData.selectSku.id;
        cartItem.skuTitle = skuData.selectSku.title;
        cartItem.marketprice = (_this.data.user.isVip && skuData.selectSku.vipprice && goods.isvip) ? skuData.selectSku.vipprice : skuData.selectSku.marketprice;
        cartItem.vipprice = skuData.selectSku.vipprice;
      }

      if (goods.maxbuy && (goods.cartNum + cartItem.total) > goods.maxbuy) {
        wx.showToast({
          title: '已经超过单次购买数量',
          icon: 'none'
        })
        return;
      }

      app.requestUrl({
        method: 'POST',
        url: '/wxapi/cart/add',
        data: cartItem,
      }).then((res) => {
        if(_this.data.showSku && skuData){//多规格
          app.globalData.cartTotal += cartItem.total;
          _this.setData({ showSku: false });
        } else {//普通
          if (plus) {//加入购物车
            app.globalData.cartTotal += 1;
          } else {//减
            app.globalData.cartTotal -= 1;
          }
        }

        _this.setData({ tabCartTotal: wx.getStorageSync('cartTotal') })

      })
    }
  },

  //规格加入购物车
  skuAddCart(event){
    if (!this.data.skuGoods.selectSku) {
      wx.showToast({
        title: '请先选择商品规格',
        icon: 'none'
      })
      return;
    }
    let goods = event.currentTarget.dataset.goods;
    if(!goods.selectNum) goods.selectNum = 1;
    let currentTarget = {currentTarget: {dataset: {goods: goods, plus: true, skuData: goods}}};
    this.addCartClick(currentTarget);
  },

  //规格数量
  onNumSkuChange(event){
    let value = event.detail;
    this.setData({
      ['skuGoods.selectNum']: value
    })
  },

  //规格选择
  skuItemClick(event){
    let skuItem = event.currentTarget.dataset.goods;
    this.setData({
      ['skuGoods.selectSku']: skuItem
    })
  },

  //立即购买
  doBuyNow (event) {
    let _this = this;

    let goods = event.currentTarget.dataset.goods;
    let isSpellgroup = goods.isSpellgroup == '1' ? goods.isSpellgroup : ''//拼团标识
    let promoter = event.currentTarget.dataset.promoter || _this.data.user.id//发起人id
    let sgorderId = event.currentTarget.dataset.sgorderId || ''//发起人订单id

    if (goods.isTeamBuy == 1 && _this.data.user.isteam !== 3) {
      Toast('抱歉，只有门店才能购买此商品！')
      return
    }

    if (!goods.hasoption) {//非多规格
      let order = {
        cartItems: [{
          cartId: goods.id,
          productId: goods.id,
          total: 1,
          skuId: goods.skuId,
          skuTitle: goods.skuTitle,
          marketprice: goods.marketprice,
        }]
      }
      wx.setStorageSync('order', JSON.stringify(order))
      wx.navigateTo({
        url: '/pages/index/place-order-entity/place-order-entity' +
        '?isSpellgroup=' + isSpellgroup + '&promoter=' + promoter + '&sgorderId=' + sgorderId
      })
    } else if (_this.data.showSku) {//多规格商品
      if (!this.data.skuGoods.selectSku) {
        wx.showToast({
          title: '请先选择商品规格',
          icon: 'none'
        })
        return;
      }
      if(!goods.selectNum) goods.selectNum = 1;
      let order = {
        cartItems: [{
          productId: goods.id,
          skuId: goods.selectSku.id,
          total: goods.selectNum,
          skuTitle: goods.selectSku.title,
          marketprice: goods.selectSku.marketprice,
          vipprice: goods.selectSku.vipprice,
        }]
      }

      wx.setStorageSync('order', JSON.stringify(order))
      wx.navigateTo({
        url: '/pages/index/place-order-entity/place-order-entity' +
        '?isSpellgroup=' + isSpellgroup + '&promoter=' + promoter + '&sgorderId=' + sgorderId
      })
    } else {
      app.requestUrl({
        method: 'GET',
        url: '/wxapi/shop/products/detail',
        data: {
          productId: goods.id,
          memberId: _this.data.user.id
        }
      }).then(res =>{
        _this.setData({
          skuGoods: goods,
          ['skuGoods.detail']: res.data.data,
          showSku: true
        })
      })
    }
  },

  isSalingFun () {
    let _this = this
    if (!_this.data.goods) {
      _this.setData({isSaling: false})
    }
    else if (_this.data.goods.total <= (_this.data.goods.salesreal)) {
      _this.setData({isSaling: false})
    }
    else {
      const endTime = moment(_this.data.goods.timeend).valueOf()
      const startTime = moment(_this.data.goods.timestart).valueOf()
      let tempB = _this.data.serverTime > startTime && _this.data.serverTime < endTime
      _this.setData({isSaling: tempB})
    }
  },
  notStartFun () {
    let _this = this
    _this.setData({
      notStart: _this.data.serverTime < moment(_this.data.goods.timestart).valueOf() && !_this.data.goods.ismiaosha
    })
  },

  //接收参加拼团参数
  assembleSuffer (event) {
    //模拟参数格式
    let tempEvent = {
      currentTarget: {
        dataset: {
          goods: event.detail.goods,
          promoter: event.detail.mid,
          sgorderId: event.detail.orderid,
        }
      }
    }
    //购买
    this.doBuyNow(tempEvent)
  },

  //获取用户信息user
  setUserInfo () {
    let _this = this
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/member',
      data: {
        id: _this.data.user.id,
        getShop: true
      }
    }).then((res) => {
      // if (res.data.shop != '') wx.setStorageSync('shopInfo', JSON.stringify(res.data.shop))
      if (res.data.data != '') wx.setStorageSync('userInfo', JSON.stringify(res.data.data))
      _this.setData({
        user: app.getUser()
      })
    })
  },

  // 获取评论
  getCommentList:function(){
    let _this = this
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/shop/products/detail/comments',
      data: {
        productId: _this.data.productId,
        level: '',
        offset: 1,
        limit: 5
      }
    }).then((res) => {
      _this.setData({ commentInfo: res.data.data });
    })
  },

  //规格弹框
  showSkuMonitor(){
    let _this = this;
    _this.setData({showSku: !_this.data.showSku})
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (event) {
    let _this = this
    _this.setData({
      heShopId: event.heShopId,
      productId: event.productId
    })
    this.getShopInfo();
  },
  getShopInfo(){
    let that = this;
    if(that.data.heShopId != app.getShop().id){
      app.requestUrl({
        method: 'GET',
        url: '/wxapi/shop/newNearest',
        data: {
          mid:that.data.heShopId,
          longitude: '112.98626',
          latitude: '28.25591',
          limit: 50,
          centreId: app.globalData.loginCentreId,
          flag: 2//1平台 2商户
        },
        load: 1
      }).then((res) => {
        wx.setStorageSync('shopInfo', JSON.stringify(res.data.data[0]));
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this
    _this.setData({
      user: app.getUser(),
      tabCartTotal: wx.getStorageSync('cartTotal'),
    })

    if (!_this.data.user.id) {//未登录
      wx.navigateTo({
        url: '/pages/login/login'
      })
    }
    else if (_this.data.user.isteam != 3 && _this.data.user.id && app.getShop().id) {//已登录+拥有分享链接门店id+不是门店身份
      app.requestUrl({
        method: 'POST',
        url: '/wxapi/shop/bind',
        data: {
          memberId: _this.data.user.id,
          teamId: app.getShop().id
        }
      }).then((res) => {
        _this.setUserInfo()
      })
    }

    _this.getCommentList();
    _this.getGoodInfo(_this.data.productId)

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var _this = this
    let share = app.getShareData()
    if (res.from === 'button') {//来自页面内转发按钮
      return {
//        title: share.shareTitle,
        title: _this.data.goodsTitle,
        path: '/subIndex/index/good-item/good-item?productId=' + _this.data.productId + '&heShopId=' + app.getShop().id,
        imageUrl: _this.data.goodsThumb,
        success: function () {

        },
        fail: function () {
          wx.showToast({title: '分享失败', icon: 'none'})
        }
      }
    }
    else if (res.from === 'menu') {//右上角菜单转发按钮
      let shop = app.getShop()
//      let shareTitle = share.shareTitle.split('{')[0] + shop.tXiaoqu + share.shareTitle.split('}')[1]
      return {
        title: _this.data.goodsTitle,
        //用户A分享时带上用户A的门店id，用户B点击链接直接绑定用户A的门店
        path: '/subIndex/index/good-item/good-item?productId=' + _this.data.productId + '&heShopId=' + app.getShop().id,
        imageUrl: _this.data.goodsThumb,
        success: function () {

        },
        fail: function () {
          wx.showToast({title: '分享失败', icon: 'none'})
        }
      }
    }
  }
})
